/** 领料申请模块 **/ 
// 导入数据库
const db = require('../db/index')
const { v4: uuidv4 } = require('uuid') // 自动生成随机id

// 新增领料申请
exports.addMaterialApply = (req,res) => {
  const data = req.body
  // 插入数据语句
  const sql = 'insert into apply_materials set ?'
  const queryData = {
    id: uuidv4(),  // 手动增加随机id
    createDate: new Date(), // 表单新增时间
    ...data,
  }
  db.query(sql,queryData, (err,results) => {
    // 执行SQL语句失败
    if(err) return res.send( { success: false,status: 10000, msg: err.message  } )
    // SQL语句执行成功，但影响行数不为1 
    if (results.affectedRows !== 1) res.send({ success: false,status: 10000, msg: '保存失败!' })

    res.send({ success:true, status: 200, msg: '保存成功！', data: results[0] })
  })

}
/* 获取领料单数据 */ 
exports.getMaterialApply = (req,res)=> {
  const data = req.body
  // 查询数据语句
  const sql = "select * from apply_materials where (IFNULL('', '') = '' OR storageCode = '') "
  db.query(sql,[data,data.storageCode],(err,results) => {
    // 执行SQL语句失败
    if(err) return res.send( { success: false,status: 10000, msg: err.message  } )

    res.send({ success: true, status: 200, msg: 'success', data: results })
  })
}

/**根据id查询数据**/ 
exports.getMaterialByIdApply = (req,res)=> {
  const data = req.body
  const query = req.query
  // 查询数据语句

  const sql = "select * from apply_materials where id=? "
  db.query(sql,query.id,(err,results) => {
    // 执行SQL语句失败
    if(err) return res.send( { success: false,status: 10000, msg: err.message  } )

    res.send({ success: true, status: 200, msg: 'success', data: results })
  })
}
